package edu.ccut.saturn.component.xml;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import edu.ccut.saturn.component.SaturnComponentException;

/**
 * Dom4j简化工具类,根据InputStream获得Document对象
 * 
 * @author 谷钰
 * 
 * @version 1.0 2008.8.28
 * 
 */
public abstract class Dom4jUtils {

	/**
	 * 把输入字节流转换成可读取的xml对象,转换失败抛出SaturnComponentException
	 * 
	 * @param in
	 *            输入字节流
	 * @return
	 * @throws SaturnComponentException
	 */
	public static Document getDocment(InputStream in)
			throws SaturnComponentException {

		SAXReader reader = new SAXReader();
		Document document = null;

		try {
			document = reader.read(in);
		} catch (Exception e) {
			throw new SaturnComponentException(e);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return document;
	}

	/**
	 * 把输入字符流换成可读取的xml对象,转换失败抛出SaturnComponentException
	 * 
	 * @param reader
	 *            输入字符流
	 * @return
	 * @throws SaturnComponentException
	 */
	public static Document getDocment(Reader reader)
			throws SaturnComponentException {

		SAXReader saxReader = new SAXReader();
		Document document = null;

		try {
			document = saxReader.read(reader);
		} catch (Exception e) {
			throw new SaturnComponentException("Failed to read xml file.", e);
		} finally {

			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return document;
	}

	// 功能重复,应该删除

	// @SuppressWarnings("unchecked")
	// public static Element readXmlForElement(String file) throws Exception {
	// Document document = null;
	// InputStream in = null;
	//
	// try {
	// in = Dom4jUtils.class.getResource(file).openStream();
	// } catch (Exception e) {
	// String serverPath = Dom4jUtils.class.getResource("/").getPath()
	// + file;
	//
	// in = new FileInputStream(serverPath);
	// }
	// document = Dom4jUtils.getDocment(in);
	//		
	// if (document == null) {
	// throw new SaturnComponentException("Can not create Document.");
	// }
	// Element root = document.getRootElement();
	//		
	// if (root == null) {
	// throw new SaturnComponentException(
	// "The config file don't have element.");
	//
	// }
	// return root;
	// }
	//
	// public static Document getDocment(Reader dataReader)
	// throws SaturnComponentException {
	//		
	// if (dataReader == null) {
	// throw new SaturnComponentException("Invalid InputStream specified?");
	// }
	//
	// SAXReader reader = new SAXReader();
	// Document document = null;
	//		
	// try {
	// document = reader.read(dataReader);
	// } catch (Exception e) {
	// throw new SaturnComponentException("Failed to read xml file.", e);
	// } finally {
	//
	// try {
	// dataReader.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	//
	// return document;
	// }
}
